package weizan

import (
	"encoding/json"
	"log"
	"server/utils/tools"
	"strconv"
	"time"
)

var account = "Vzan633977840"
var key = "77bd352a60cb4f2982cba99508bf2a3c"
var accToken = ""
var tokenExpires = ""

func GetToken() (string, error) {

	if accToken != "" {
		if tokenExpires != "" {
			expires, err := time.Parse("2006-01-02 15:04:05", tokenExpires)
			if err != nil {
				log.Println(err)
				return "", err
			}
			if expires.Unix() > (time.Now().Unix() - 3600) {
				return accToken, nil
			}
		}
	}

	url := "https://openapi.vzan.com/api/v2/token/get_token"
	param := make(map[string]any)
	herader := make(map[string]string)
	timestamp := time.Now().Unix()
	param["account"] = account
	param["signkey"] = tools.GetMd5String(key + strconv.FormatInt(timestamp, 10))
	param["timestamp"] = timestamp
	resp, err := tools.PostJson(url, herader, param, "POST")
	var token Token
	err = json.Unmarshal(resp, &token)
	if err != nil {
		log.Println(err)
		return "", err
	}

	accToken = token.Data.Token
	tokenExpires = token.Data.TokenExpires
	return token.Data.Token, nil
}

type Token struct {
	Msg  string `json:"msg"`
	Code int    `json:"code"`
	Data struct {
		Token        string `json:"token"`
		TokenExpires string `json:"tokenExpires"`
	} `json:"data"`
}
